$(function () {

    const form = layui.form;
    const layer = layui.layer
    const element = layui.element;
  
    const E = window.wangEditor
    const editor = new E("#div1")
    // 或者 const editor = new E(document.getElementById('div1'))
    editor.create()
  
    axios.get('/index/index').then(({ data: { data: { allCate, allTag } } }) => {
      const Str1 = allCate.map(({ id, catename }) => `<option value="${id}">${catename}</option>`)
      $('#cateid').append(Str1)
  
      const Str2 = allTag.map(({ id, tagname }) => `<input type="checkbox" name="tags${id}" value="${tagname}" lay-skin="primary" title="${tagname}"/>`)
      $('#tags_box').html(Str2)
  
      form.render()
    })
  
    let status
    $('#submit1').on('click', function () {
      status = 2
    })
  
    $('#submit2').on('click', function () {
      status = 1
    })
  
    $('#upImage').on('click', function () {
      $('.upImage').click()
    })
  
    let pic
    $('.upImage').on('change', function () {
      const image = $(this)[0].files[0]
      const imgUrl = URL.createObjectURL(image)
      $('#preview').prop('src', imgUrl)
  
      const fd = new FormData()
      fd.append('file', image)
  
      axios.post('/common/upload?type=images', fd, {
        onUploadProgress: progressEvent => {
          let persent = (progressEvent.loaded / progressEvent.total * 100 | 0)
          element.progress('demo', `${persent}%`)
        }
      }).then(({ data: { data: { savePath } } }) => {
        pic = savePath
      })
    })
  
    $('form').on('submit', function (e) {
      e.preventDefault()
  
      const data1 = form.val("form")
      const tags = getTags(...Object.values(data1)).join(',')
      const author = JSON.parse(localStorage.getItem('userInfo'))
      console.log(author);
      const content = editor.txt.html()
  
      if (!data1.title) {
        return layer.msg('请输入文章标题')
      } else if (!data1.cateid) {
        return layer.msg('请选择文章分类')
      } else if (!tags) {
        return layer.msg('请选择标签')
      } else if (!content) {
        return layer.msg('请输入文章内容')
      } else if (!pic) {
        return layer.msg('请上传文章封面/等待文章封面上传完毕')
      }
  
      let data = {
        author: 'Adong',
        cateid: +data1.cateid,
        content,
        pic,
        status,
        tags,
        title: data1.title
      }
      axios.post('/user/addArticle', data).then(({ data: { errno, errmsg } }) => {
        if (errno !== 0) return layer.msg(errmsg)
  
        layer.msg('添加成功！2秒后跳转至文章列表', {
          time: 2000
        }, function () {
          location.href = '/web-static/user-list.html'
        })
      })
    })
  
    function getTags(x, y, ...tagArr) {
      return tagArr
    }
  
  })